<template>
	<view class="relative">
		<image
			class="block"
			:src="innerSrc"
			mode="scaleToFill"
			:style="{ width: mainImgWidth + 'px', height: mainImgHeight + 'px' }"
			@load="mainImgLoad"
			@error="mainImgError"
		/>
		<view v-if="mask" class="absolute inset-0 main-img-mask"></view>
		<view class='absolute left-0 right-0 bottom-0'>
			<slot name='bottom' />
		</view>
	</view>
</template>

<script>
import { ref, watch } from 'vue';
import Skeleton from '../skeleton/skeleton.vue';
export default {
	components: {
		Skeleton,
	},
	props: {
		src: String,
		mask: {
			default: true,
			type: Boolean,
		},
		fallback: {
			required: true,
			type: String,
		},
	},
	setup(props, ctx) {
		const info = uni.getSystemInfoSync();
		const loading = ref(false);
		const mainImgWidth = ref(info.screenWidth);
		const mainImgHeight = ref(uni.upx2px(400));
		const innerSrc = ref(props.src || props.fallback);
		watch(() => props.src,(v) => {
			innerSrc.value = v || props.fallback;
		});
		return {
			mainImgHeight,
			mainImgWidth,
			loading,
			innerSrc,
			mainImgLoad(e) {
				mainImgHeight.value = (e.detail.height / e.detail.width) * mainImgWidth.value;
				loading.value = false;
				ctx.emit('load', {
					height: mainImgHeight.value,
				});
			},
			mainImgError() {
				loading.value = false;
				innerSrc.value = props.fallback;
			},
		};
	},
};
</script>

<style>
.main-img-mask {
	background: linear-gradient(rgba(0, 0, 0, 0.2), rgba(0, 0, 0, 0.5));
}
</style>
